import router from './routers'
import store from '@/store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
  getToken
} from '@/utils/auth' // getToken from cookie
import {
  filterAsyncRouter,
  ShowfilterAsyncRouter
} from '@/store/modules/permission'
import {
  router_statilc
} from './router_static'

import { 
  setTitle
} from '@/utils/setRouteTitle'
NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach((to, from, next) => {
  store.dispatch('setQuery', false)
  const title = localStorage.getItem("terminal_name") || "LinkAOS"
  if (to.meta.title) {
    document.title = to.meta.title + ' - ' + title
  }
  NProgress.start()
  if (getToken()) {
    // 已登录且要跳转的页面是登录页
    if (to.path === '/login') {
      next({
        path: '/'
      })
      NProgress.done()
    } else {
      console.log(store.getters.roles.lengt)
      if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(res => { // 拉取user_info
          // 动态路由，拉取菜单
          loadMenus(next, to)
        }).catch((err) => {
          console.log(err, 'err')
          store.dispatch('LogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
        // 登录时未拉取 菜单，在此处拉取
      } else if (store.getters.loadMenus) {
        // 修改成false，防止死循环
        store.dispatch('updateLoadMenus').then(res => {})
        loadMenus(next, to)
      } else {
        next()
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

export const loadMenus = (next, to) => {
  //console.log(next, to,'555')
  if (process.env.VUE_APP_PERMISSION == 'true') { // 有权限 加载后端数据的路由
    const asyncRouter = filterAsyncRouter(store.state.user.user.permissions)
    asyncRouter.push({
      path: '*',
      redirect: '/401',
      hidden: true
    })
    store.dispatch('GenerateRoutes', asyncRouter).then(() => { // 存储路由
      router.addRoutes(asyncRouter) // 动态添加可访问路由表
      next({
        ...to,
        replace: true
      })
    })
  } else { // 无权限 加载自己的路由
    const asyncRouter = ShowfilterAsyncRouter(router_statilc)
    asyncRouter.push({
      path: '*',
      redirect: '/401',
      hidden: true
    })
    store.dispatch('GenerateRoutes', asyncRouter).then(() => { // 存储路由
      router.addRoutes(asyncRouter) // 动态添加可访问路由表
      next({
        ...to,
        replace: true
      })
    })
  }
}
router.afterEach((to) => {
  setTitle(to, router.app, router)
  NProgress.done() // finish progress bar
  window.scrollTo(0, 0)
})
